import React, { Component } from 'react';
import {
    Form, Icon, Input, Alert,
    Button, Dropdown, Menu, Table,
    Pagination, notification,
    Modal, Row, Col, Tag,
    InputNumber, Switch, Radio
} from 'antd';
import axios from '../axios.config';
import JavascriptCommon from '../javascript.common';

class Permit extends Component {
    constructor(props) {
        super(props);
        this.state = {
            columns: [{
                title: "主键",
                dataIndex: "ZK_ID",
                sorter: true
            }, {
                title: "路径",
                dataIndex: "ZK_PATH",
                sorter: true
            }, {
                title: "名称",
                dataIndex: "ZK_NAME",
                sorter: true
            }, {
                title: "组件",
                dataIndex: "ZK_COMPONENT",
                sorter: true
            }, {
                title: "状态",
                dataIndex: "ZK_ISHIDDEN",
                sorter: true,
                render: text => text === "0" ? <Tag color="blue">显示</Tag> : <Tag color="green">隐藏</Tag>
            }, {
                title: "图标",
                dataIndex: "ZK_ICON",
                sorter: true
            }, {
                title: "类型",
                dataIndex: "ZK_ISLEAF",
                sorter: true,
                render: text => text === "1" ? <Tag color="blue">叶子节点</Tag> : <Tag color="green">普通节点</Tag>
            }, {
                title: "父级",
                dataIndex: "ZK_PARENT",
                sorter: true
            }, {
                title: "操作",
                width: 120,
                render: (text, record, index) => (<Button.Group>
                    <Button type="primary" icon="edit" onClick={() => { this.getRecord(record, index); }} />
                    <Button type="primary" icon="delete" onClick={() => { this.delRecord(record, index); }} />
                </Button.Group>)
            }],
            selection: [],
            records: [],
            tableParam: {
                keyword: "",
                _keyword: "",
                prop: "",
                order: "",
                pagesize: 15,
                pageno: 1,
                total: 0,
                loading: false,
                dropdown: [
                    { key: "ZK_ID", value: "主键" },
                    { key: "ZK_PATH", value: "路径" },
                    { key: "ZK_COMPONENT", value: "组件" },
                    { key: "ZK_NAME", value: "名称" }
                ],
                keycurrent: 0
            },
            recordForm: {
                flag: true,
                record: {},
                visible: false,
                index: -1
            }
        };
    }
    componentDidMount() {
        this.query();
    }
    query() {
        this.state.tableParam.loading = true;
        this.setState({ tableParam: this.state.tableParam });
        axios.get("Http/Msg/PermitServer.ashx?method=Backend_GetPermitList", {
            params: {
                KEYWORD: this.state.tableParam.keyword,
                TYPE: this.state.tableParam.dropdown[this.state.tableParam.keycurrent].key,
                PROP: this.state.tableParam.prop,
                ORDER: this.state.tableParam.order,
                PAGESIZE: this.state.tableParam.pagesize,
                PAGENO: this.state.tableParam.pageno
            }
        }).then(res => {
            this.state.tableParam.loading = false;
            this.setState({ tableParam: this.state.tableParam });
            if (res.data.flag === "True") {
                this.state.tableParam.total = parseInt(res.data.message);
                this.setState({ records: res.data.result });
            }
        });
    }
    currentChange(currentPage) {
        if (this.state.tableParam.pageno !== currentPage) {
            this.state.tableParam.pageno = currentPage;
            this.setState({ tableParam: this.state.tableParam }, () => {
                this.query();
            });
        }
    }
    sortChange(s) {
        if ("field" in s && s.field && s.order) {
            this.state.tableParam.prop = s.field;
            this.state.tableParam.order = s.order + "ing"
            this.state.tableParam.pageno = 1;
            this.query();
        }
    }
    formatterDate(value) {
        return JavascriptCommon.ChangeDateFormat_hhmmss(value, "-");
    }
    delRecord(record, index) {
        Modal.confirm({
            title: "权限删除警告",
            content: "除非确保安全，否则我们不建议您进行此操作，一切后果自行负责！",
            okText: "确定",
            cancelText: "取消",
            onOk: () => {
                axios.post("Http/Msg/PermitServer.ashx?method=Backend_DeletePermit", { IDS: record.ZK_ID }).then(res => {
                    if (res.data.flag === "True") {
                        this.state.records.splice(index, 1);
                        this.setState({ records: this.state.records }, () => {
                            notification.success({
                                message: "成功",
                                description: "已成功删除一条权限信息"
                            });
                        });
                    }
                });
            }
        });
    }
    batchDelete() {
        Modal.confirm({
            title: "权限删除警告",
            content: "除非确保安全，否则我们不建议您进行此操作，一切后果自行负责！",
            okText: "确定",
            cancelText: "取消",
            onOk: () => {
                axios.post("Http/Msg/PermitServer.ashx?method=Backend_DeletePermit", { IDS: this.state.selection.join(",") }).then(res => {
                    if (res.data.flag === "True") {
                        notification.success({
                            message: "成功",
                            description: "成功删除多条记录(一秒后将自动刷新页面)"
                        });
                        setTimeout(() => {
                            window.location.reload();
                        }, 1200);
                    }
                });
            }
        });
    }
    getRecord(record, index) {
        axios.get("Http/Msg/PermitServer.ashx?method=Backend_GetPermitDetail", { params: { UID: record.ZK_ID } }).then(res => {
            if (res.data.flag === "True") {
                this.state.recordForm.record = res.data.result;
                this.state.recordForm.flag = false;
                this.state.recordForm.visible = true;
                this.state.recordForm.index = index;
                this.setState({ recordForm: this.state.recordForm });
            }
        });
    }
    insertRecord(e) {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            if (err) { return false; }
            for (let key in values) {
                this.state.recordForm.record[key] = values[key];
            }
            axios.post("Http/Msg/PermitServer.ashx?method=Backend_InsertPermit", this.state.recordForm.record).then(res => {
                if (res.data.flag === "True") {
                    notification.success({
                        message: "成功",
                        description: "新增成功(一秒后将自动刷新页面)"
                    });
                    this.state.recordForm.visible = false;
                    this.state.records.unshift(this.state.recordForm.record);
                    this.setState({ recordForm: this.state.recordForm, records: this.state.records });
                    setTimeout(() => { window.location.reload(); }, 1200);
                }
            });
        });
    }
    updateRecord(e) {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            if (err) { return false; }
            for (let key in values) {
                this.state.recordForm.record[key] = values[key];
            }
            axios.post("Http/Msg/PermitServer.ashx?method=Backend_UpdatePermit", this.state.recordForm.record).then(res => {
                if (res.data.flag === "True") {
                    notification.success({
                        message: "成功",
                        description: "更新权限成功"
                    });
                    this.state.recordForm.visible = false;
                    this.state.records[this.state.recordForm.index] = this.state.recordForm.record;
                    this.setState({ recordForm: this.state.recordForm, records: this.state.records });
                }
            });
        });
    }
    render() {
        const { getFieldDecorator } = this.props.form;
        return (
            <div id="params_temp">
                <div className="toolbar">
                    <Form layout="inline">
                        <Form.Item>
                            <Input
                                placeholder={"请输入关键字（" + this.state.tableParam.dropdown[this.state.tableParam.keycurrent].value + "）"}
                                value={this.state.tableParam._keyword}
                                onChange={e => { this.state.tableParam._keyword = e.target.value; this.setState({ tableParam: this.state.tableParam }); }}
                            />
                        </Form.Item>
                        <Form.Item>
                            <Dropdown overlay={<Menu>
                                {this.state.tableParam.dropdown.map((item, index) => (
                                    <Menu.Item key={item.key} onClick={() => {
                                        this.state.tableParam.pageno = 1;
                                        this.state.tableParam.keycurrent = index;
                                        this.state.tableParam.keyword = this.state.tableParam._keyword;
                                        this.setState({ tableParam: this.state.tableParam }, () => { this.query(); });
                                    }} >
                                        {this.state.tableParam.keycurrent === index ? <b>{item.value}</b> : item.value}
                                    </Menu.Item>
                                ))}
                            </Menu>}>
                                <Button type="primary" onClick={() => {
                                    this.state.tableParam.pageno = 1;
                                    this.state.tableParam.keyword = this.state.tableParam._keyword;
                                    this.setState({ tableParam: this.state.tableParam }, () => { this.query(); });
                                }} >
                                    <Icon type="search" />查询<Icon type="down" />
                                </Button>
                            </Dropdown>
                        </Form.Item>
                        <Form.Item>
                            <Button type="primary" onClick={() => {
                                this.state.recordForm.flag = true;
                                this.state.recordForm.record = {};
                                this.state.recordForm.visible = true;
                                this.setState({ recordForm: this.state.recordForm });
                            }}>新增</Button>
                        </Form.Item>
                        <Form.Item>
                            <Alert message="谨慎操作，尽量避免删除或修改正在使用的权限，防止不可逆情况的发生" type="warn" showIcon />
                        </Form.Item>
                    </Form>
                </div>
                <Table
                    columns={this.state.columns}
                    dataSource={this.state.records}
                    rowKey={record => record.ZK_ID}
                    loading={this.state.tableParam.loading}
                    pagination={false}
                    rowSelection={{ onChange: keys => { this.setState({ selection: keys }); } }}
                    onChange={(p, f, s) => { this.sortChange(s); }}>
                </Table>
                <div className="botton_toolbar">
                    <Button type="danger" icon="delete" disabled={this.state.selection.length === 0} onClick={() => { this.batchDelete(); }}>
                        批量删除{this.state.selection.length > 0 ? "(共" + this.state.selection.length + "条)" : ""}
                    </Button>
                    <Pagination
                        size="small"
                        style={{ float: "right" }}
                        total={this.state.tableParam.total}
                        current={this.state.tableParam.pageno}
                        pageSize={this.state.tableParam.pagesize}
                        showQuickJumper
                        showTotal={total => (<span className="recordtotal">共{total}条记录</span>)}
                        onChange={page => { this.currentChange(page); }}
                    />
                </div>
                <Modal
                    title={this.state.recordForm.flag ? "新增" : "编辑"}
                    visible={this.state.recordForm.visible}
                    footer={null}
                    maskClosable={false}
                    destroyOnClose={true}
                    onCancel={() => { this.state.recordForm.visible = false; this.setState({ recordForm: this.state.recordForm }); }}
                >
                    <Form onSubmit={e => {
                        if (this.state.recordForm.flag) {
                            this.insertRecord(e)
                        } else {
                            this.updateRecord(e);
                        }
                    }}>
                        <Form.Item
                            label="主　键"
                            labelCol={{ span: 4 }}
                            wrapperCol={{ span: 20 }}>
                            {getFieldDecorator("ZK_ID", {
                                initialValue: this.state.recordForm.record.ZK_ID,
                                rules: [{ required: true, message: "请输入主键" }]
                            })(<Input disabled={!this.state.recordForm.flag} />)}
                        </Form.Item>
                        <Form.Item
                            label="名　称"
                            labelCol={{ span: 4 }}
                            wrapperCol={{ span: 20 }}>
                            {getFieldDecorator("ZK_NAME", {
                                initialValue: this.state.recordForm.record.ZK_NAME,
                                rules: [{ required: true, message: "请输入名称" }]
                            })(<Input />)}
                        </Form.Item>
                        <Form.Item
                            label="路　径"
                            labelCol={{ span: 4 }}
                            wrapperCol={{ span: 20 }}>
                            {getFieldDecorator("ZK_PATH", {
                                initialValue: this.state.recordForm.record.ZK_PATH,
                                rules: [{ required: true, message: "请输入路径" }]
                            })(<Input />)}
                        </Form.Item>
                        <Form.Item
                            label="组　件"
                            labelCol={{ span: 4 }}
                            wrapperCol={{ span: 20 }}>
                            {getFieldDecorator("ZK_COMPONENT", {
                                initialValue: this.state.recordForm.record.ZK_COMPONENT,
                                rules: [{ required: true, message: "请输入组件（详情询问前台）" }]
                            })(<Input />)}
                        </Form.Item>
                        <Form.Item
                            label="隐　藏"
                            labelCol={{ span: 4 }}
                            wrapperCol={{ span: 20 }}>
                            <Row gutter={12}>
                                <Col span="12">
                                    <Switch
                                        defaultChecked={this.state.recordForm.record.ZK_ISHIDDEN === "1"}
                                        onChange={(flag) => { this.state.recordForm.record.ZK_ISHIDDEN = flag ? "1" : "0"; }}
                                    />
                                </Col>
                                <Col span="12">
                                    <i className={this.state.recordForm.record.ZK_ICON}></i>
                                </Col>
                            </Row>
                        </Form.Item>
                        <Form.Item
                            label="图　标"
                            labelCol={{ span: 4 }}
                            wrapperCol={{ span: 20 }}>
                            {getFieldDecorator("ZK_ICON", {
                                initialValue: this.state.recordForm.record.ZK_ICON
                            })(<Input />)}
                        </Form.Item>
                        <Form.Item
                            label="类　型"
                            labelCol={{ span: 4 }}
                            wrapperCol={{ span: 20 }}>
                            {getFieldDecorator("ZK_ISLEAF", {
                                initialValue: this.state.recordForm.record.ZK_ISLEAF || "0"
                            })(<Radio.Group>
                                <Radio value="1">叶子节点</Radio>
                                <Radio value="0">普通节点</Radio>
                            </Radio.Group>)}
                        </Form.Item>
                        <Form.Item
                            label="权　重"
                            labelCol={{ span: 4 }}
                            wrapperCol={{ span: 20 }}>
                            {getFieldDecorator("ZK_SORT", {
                                initialValue: this.state.recordForm.record.ZK_SORT,
                                rules: [{ required: true, message: "请输入权重（数字越小等级越靠前）" }]
                            })(<InputNumber min={0} />)}
                        </Form.Item>
                        <Form.Item
                            label="父　级"
                            labelCol={{ span: 4 }}
                            wrapperCol={{ span: 20 }}>
                            {getFieldDecorator("ZK_PARENT", {
                                initialValue: this.state.recordForm.record.ZK_PARENT
                            })(<Input placeholder="请输入父级主键" />)}
                        </Form.Item>
                        <Form.Item>
                            <Row style={{ textAlign: "center" }}>
                                <Col span={12}>
                                    <Button icon="rollback" onClick={() => {
                                        this.state.recordForm.visible = false; this.setState({ recordForm: this.state.recordForm });
                                    }}>
                                        返回
                                    </Button>
                                </Col>
                                <Col span={12}>
                                    <Button type="primary" htmlType="submit" icon="save">保存</Button>
                                </Col>
                            </Row>
                        </Form.Item>
                    </Form>
                </Modal>
            </div >
        );
    }
}

Permit = Form.create()(Permit);

export default Permit;

